﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using RayD.Core;
using StackExchange.Profiling;
using System;

namespace RayD.App.Setup
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class ApiExceptionFilter : IExceptionFilter
    {
        public void OnException(ExceptionContext context)
        {
            //性能分析中收录异常
            MiniProfiler.Current.CustomTiming("Errors：", context.Exception.Message);

            #region 根据项目所处环境处理结果
            //判断项目所处环境
            //var _bool = string.Equals(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"), "Development");
            //var _msg = string.Empty;
            //if (!_bool) _msg = "请求处理异常，请联系系统管理员！";
            //else _msg = context.Exception.Message;
            //根据项目所处环境处理结果
            context.Result = new ContentResult()
            {
                ContentType = "application/json",
                Content = new ResParameter { code = ResponseCode.exception, msg = context.Exception.Message, data = null }.ToJson()
            };
            #endregion

            //返回500状态码
            context.HttpContext.Response.StatusCode = (int)ResponseCode.exception;
        }
    }
}
